/**
 * @(#)LoginController.java, 2018/2/3.
 * <p/>
 * Copyright 2018 Kerr Wang, Inc. All rights reserved.
 * KERRWANG PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package org.wangzx.exercise.controller;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.wangzx.exercise.meta.bean.UserBean;
import org.wangzx.exercise.service.core.UserCoreService;
import org.wangzx.exercise.utils.DigestUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hzwangzuxiang(ahscwzx@163.com)
 */
@Controller
@RequestMapping("/")
public class LoginController extends BaseController {
    static private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserCoreService userCoreService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView getLoginPage() {
        logger.info("[op:getLoginPage] get login page");
        return genModelAndView("/tmpl/login");
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> loginAPI(HttpServletRequest request, HttpServletResponse response,
        @RequestParam String userName, @RequestParam String password) {
        logger.info("[op:loginAPI] userName={}, password={}", userName, password);
        UserBean bean = userCoreService.getByName(userName);
        logger.info("[op:loginAPI] userbean={}", JSON.toJSONString(bean));
        Map<String, Object> map = new HashMap<>();
        if (bean == null || bean.getPassword() == null) {
            map.put("code", 401);
            map.put("result", false);
            map.put("message", "无此用户，请确认");
        } else if (!DigestUtils.md5(bean.getPassword()).equals(password)) {
            map.put("code", 401);
            map.put("result", false);
            map.put("message", "密码错误，请重试");
        } else {
            //增加session跟踪
            HttpSession session = request.getSession(true);
            session.setAttribute("userType", bean.getType().getValue());
            session.setAttribute("userName", bean.getName());

            logger.info("[op:loginAPI] userName={} login success", userName);

            map.put("code", 200);
            map.put("result", true);
            map.put("message", "登录成功");
        }
        return map;
    }

    @RequestMapping("/logout")
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        Cookie cookies[] = null;
        cookies = request.getCookies();
        if(cookies != null) {
            for(Cookie cookie : cookies) {
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
        return new ModelAndView(new RedirectView("/"));
    }
}
